<?php

class ClientsController extends AppController
{
	var $name = "Clients";
	var $uses = array("Client", "Survey", "Item", "Choice", "Cronjob", "Rectangle", "User");
	var $components = array('Email');
	
	function index()
	{
		$client_id = $this->Session->read("current_client_id");
		$this->set('current_client', $this->Client->findById($client_id));
	}
	
	function show_clients()
	{
		$clients = $this->Client->find('all');
		$this->set(compact('clients'));
	}
	
	function show_items()
	{
		$s_items = $this->Item->find('all');
		$this->set('s_items', $s_items);
	}

	// ADDING A CLIENT
	function add()
	{
		if (!empty($this->data))
		{
			$this->Client->create();
			
			if ($this->Client->save($this->data))
			{
				$this->Session->setFlash(_('saved', true));
				$this->redirect(array('action'=>'index'));
			}
			else
			{
				$this->Session->setFlash(_('not saved', true));
			}
		}
	}
	
	function view_client(){}
	
	function new_survey(){}
	
	function add_survey()
	{
		if (!empty($this->data))
		{
			$this->data['Survey']['client_id'] = $this->Session->read('current_client_id');
			//$this->data['Survey']['client_id'] = $this->Auth->client('id');
			
			if(!empty($_POST['alarms']))
				$new_survey = $this->Cronjob->setSurveyAlarms($_POST['alarms'], $this->data);
			else
				$new_survey = $this->data;
			$this->Survey->saveAll($new_survey);
			$new_survey = $this->Survey->find('first', array('conditions'=>$this->data['Survey'], 'order'=>array('Survey.id DESC')));
			$s_id = $new_survey['Survey']['id'];
			$this->redirect("/clients/new_item/$s_id");
			//$this->set('data', $this->data);
		}
	}
	
	function new_item($s_id){
		$this->set('s_id', $s_id);	
	}
	
	function remove_survey($s_id){
		$this->Survey->del($s_id, true);
		$this->Survey->query("DROP TABLE results$s_id;");
		exec("rm -r ../../files/$s_id");
		$this->redirect("/clients/index");
	}
	
	function results($survey_id)
	{
		$this->set('survey_id', $survey_id); // survey_id variable being set for use in view ctp file
		
		// setting a table variable for use in the view ctp file
		$table = "results".$survey_id;
		$this->set('table', $table);
	
		// query to select all the rows from results table
		$result = mysql_query("SELECT * FROM results".$survey_id);
		$this->set('result', $result);

		// setting variable num_col which holds the number of columns in results table
		// each results table is unique and the # of columns vary
		$num_col = mysql_num_fields($result);
		$this->set('num_col', $num_col);
		
		// setting the num_rows variable to the number of rows
		$num_rows = mysql_num_rows($result);
		$this->set('num_rows', $num_rows);
		
		// getting an array that holds the item numbers
		$item_numbers = array();
		$item_numbers = $this->Item->get_item_numbers($num_col, $result);
		$this->set('item_numbers', $item_numbers);
		
		// getting an array holding the item titles
		$item_titles = array();
		$item_titles = $this->Item->get_item_titles($num_col, $item_numbers);
		$this->set('item_titles', $item_titles);
		
		// getting a 2-dimensional array that holds all the results to be shown by (field by row)
		$fields = array();
		$fields = $this->Item->get_fields($num_rows, $num_col, $item_numbers, $result);
		$this->set('fields', $fields);

		$query = mysql_query("SELECT Name FROM surveys WHERE Id = {$survey_id}");
		$survey_name = mysql_result($query, 0);
		$this->set('survey_name', $survey_name);
	}
	
	function add_item(){
		if(!empty($this->data)){
			$s_id = $this->data['Item']['survey_id'];
			$last_item = $this->Item->last_item($s_id);
			$new_item = $this->Item->process($this->data, $_POST['choices'], $_FILES['prompt_image']);
			$this->Item->saveAll($new_item);
			$new_item = $this->Item->last_item($s_id);
			if($new_item['Item']['returns']==0)
				$this->Choice->addSome($_POST['choices'], $new_item['Item']['id']);
			if(!empty($last_item)){
				$last_item['Item']['next'] = $new_item['Item']['id'];
				$this->Item->save($last_item);
			}
			if($_POST['done']==1){
				$this->Survey->finalize($s_id);
				$this->redirect("/clients/index");
			}
			else{
				if($new_item['Item']['returns']=='4'){
					$item_id = $new_item['Item']['id'];
					$survey_id = $new_item['Item']['survey_id'];
					$fname = $_FILES['prompt_image']['name'];
					$ext = strrchr($fname, '.');
					exec("cp ../../files/$survey_id/$fname ../../files/tmp/$item_id"."$ext");
					$this->redirect("/clients/new_rectangles/$item_id");
				}
				else
					$this->redirect("/clients/new_item/$s_id");
			}
		}
		//$this->set('data', $this->data);
	}
	
	function new_rectangles($item_id){
		$this->set('item_id', $item_id);
		$file = shell_exec("ls ../../files/tmp/$item_id*");
		$file = strrchr($file, '/');
		$this->set('image_file', "/tmp$file");
	}
	
	function set_rectangles($item_id){
		$i = $this->Item->findById($item_id);
		$survey_id = $i['Item']['survey_id'];
		$data = $this->data;
		foreach($data as $i=>$rec){
			$data[$i]['Rectangle']['survey_id'] = $survey_id;
		}
		$this->Rectangle->saveAll($data);
		//$this->set('data', $data);
		if($_POST['done']==1){
			$this->Survey->finalize($survey_id);
			$this->redirect("/clients/index");
		}
		else
			$this->redirect("/clients/new_item/$survey_id");
	}
	
	function order_items($survey_id){
		$survey = $this->Survey->findById($survey_id);
		$this->set('items', $survey['Item']);
	}
	
	function get_order_form($item_id){
		$this->set('item', $this->Item->findById($item_id));
	}
	
	function view()
	{
		$client_id = 2;
		$surveys = $this->Survey->findAllByClientId($client_id);
		$this->set('current_client', $this->Client->findById($client_id));
		$this->set(compact('surveys'));
	}
	
	function signup()
	{
		if (!empty($this->data))
		{
			//if (isset($this->data['client']['password2']))
			//	$this->data['Client']['password2hashed'] = $this->Auth->password($this->data['Client']['password2']);
				
			$this->data['Client']['confirm_code'] = String::uuid();
			
			$this->Client->create();
			
			if ($this->Client->save($this->data))
			{
				$this->Email->to = $this->data['Client']['email'];
				$this->Email->subject = 'Steroid Client Confirmation';
				$this->Email->replyTo = 'noreply@steroid.trombonium.net';
				$this->Email->from = 'Steroid <noreply@steroid.trombonium.net>';
				$this->Email->sendAs = 'html';
				$this->Email->template = 'client_confirmation';
				
				$this->set('name', $this->data['Client']['username']);
				$this->set('server_name', $_SERVER['SERVER_NAME']);
				$this->set('id', $this->Client->getLastInsertID());
				$this->set('code', $this->data['Client']['confirm_code']);
				
				if ($this->Email->send())
				{
					$this->Session->setFlash('Confirmation sent to email.  Check it.');
					$this->redirect('/clients/check_email');
					//$this->redirect(array('controller' => 'clients', 'action' => 'home'));
				}
				else
				{
					$this->Client->del($this->Client->getLastInsertID());
					$this->Session->setFlash('Problem sending confirmation. Try again');
				}			
				/*
				$this->Session->setFlash('Congratulations! You have signed up!');
				$this->redirect(array('controller' => 'questions', 'action' => 'home'));
				*/
			}
			else
			{
				$this->Session->setFlash('There was an error signing up.  Please, try again.');
				
				$this->data = null;
			}
		}
	}
	
	function confirm($client_id = null, $code = null)
	{
		if(empty($client_id) || empty($code))
		{
			$this->set('confirmed', 0);
				$this->render();
		}
		
		$client = $this->Client->read(null, $client_id);
		
		if(empty($client))
		{
			$this->set('confirmed', 0);
				$this->render();
		}

		if($client['Client']['confirm_code'] == $code)
		{
			$this->Client->id = $client_id;
			$this->Client->saveField('confirmed', '1');
			$this->Set('confirmed', 1);
		}
		else
		{
			$this->set('confirmed', 0);
		}
	}
	
	function disp_user($id){
		$this->set('data', $this->User->findById($id));
	}
	
	function login()
	{	
	}
	
	function logout()
	{
		$this->Session->setFlash('Logout');
		$this->redirect($this->Auth->logout());
	}
	
	function check_email()
	{
	}
}

?>
